#!/usr/bin/php
<?PHP

const ROW = 12;
const COL = 50;


function init(& $bg)
{
    $r = ROW - 1;
    $c = COL - 1;
    for ($i = 0; $i < ROW; ++$i) {
        for ($j = 0; $j < COL; ++$j) {
            $bg[$i][$j] = ($i == 0 || $j == 0
                                || $i == $r || $j == $c)
                           ? '#' : ' ';
        }
    }
}

function draw(& $bg, & $ball)
{
    $bg[$ball['r']][$ball['c']] = '@';
}


function show(& $bg, & $ball)
{
    echo "\033[2J\033[1;1H";
    for ($i = 0; $i < ROW; ++$i) {
        for ($j = 0; $j < COL; ++$j) {
            if ($bg[$i][$j] == '@')
                printf("\033[%dm@\033[0m", $ball['color']);
            else
                echo $bg[$i][$j];
        }
        echo "\n";
    }
}

function move(& $ball)
{
    if ($ball['r'] + $ball['r_inc'] < 0
            || $ball['r'] + $ball['r_inc'] > ROW - 1)
    {
        $ball['r_inc'] = -1 * $ball['r_inc'];
        $ball['color'] = mt_rand(30, 37);
    }

    if ($ball['c'] + $ball['c_inc'] < 0
            || $ball['c'] + $ball['c_inc'] == COL - 1)
    {
        $ball['c_inc'] = -1 * $ball['c_inc'];
        $ball['color'] = mt_rand(30, 37);
    }

    $ball['r'] += $ball['r_inc'];
    $ball['c'] += $ball['c_inc'];
}

function main()
{
    $bg = array();
    $ball = array(
        'r' => 3,
        'c' => 5,
        'r_inc' => 1,
        'c_inc' => 1,
        'color' => 30
    );
    $quit = TRUE;

    while ($quit)
    {
        init($bg);
        draw($bg, $ball);
        move($ball);
        show($bg, $ball);
        usleep(100000);
    }

    return 0;
}

exit(main());
